# pages/camera.py
from PySide6.QtCore import QUrl, Qt, Signal, Slot, QSize
from PySide6.QtWidgets import (QSlider, QComboBox, QPushButton, QFileDialog, 
                              QVBoxLayout, QWidget, QLabel)
from PySide6.QtGui import QIcon, QPixmap
from PySide6.QtMultimedia import QMediaPlayer, QMediaPlayer
from PySide6.QtMultimediaWidgets import QVideoWidget
from PySide6.QtMultimedia import QAudioOutput


class BaseButtonManager:
    def __init__(self, ui_section, page_instance):
        self.ui = ui_section
        self.page = page_instance
        self.button = None
    
    def init_button(self):
        raise NotImplementedError
        
    def connect_signals(self):
        raise NotImplementedError

class VideoImportManager(BaseButtonManager):
    def init_button(self):
        self.button = self.ui.findChild(QPushButton, "pushButton_24")
        if not self.button:
            raise ValueError("视频导入按钮未找到")
        return self.button
    
    def connect_signals(self):
        self.button.clicked.connect(self._handle_import)
    
    def _handle_import(self):
        """处理视频导入"""
        file_name, _ = QFileDialog.getOpenFileName(
            None,
            "选择视频文件",
            "",
            "视频文件 (*.mp4 *.avi *.mkv);;所有文件 (*)"
        )
        
        if file_name:
            # 原有播放器设置
            self.page._setup_video_components()
            self.page.media_player.setSource(QUrl.fromLocalFile(file_name))
            self.page.media_player.play()
            self.page._update_ui_state(True)

class AudioImportManager(BaseButtonManager):
    def init_button(self):
        self.button = self.ui.findChild(QPushButton, "pushButton_26")
        if not self.button:
            raise ValueError("音频导入按钮未找到")
        return self.button
    
    def connect_signals(self):
        self.button.clicked.connect(self._handle_import)
    
    def _handle_import(self):
        """处理音频导入"""
        file_name, _ = QFileDialog.getOpenFileName(
            None,
            "选择音频文件",
            "",
            "音频文件 (*.mp3 *.wav *.ogg);;所有文件 (*)"
        )
        
        if file_name:
            self.page._setup_video_components()
            self.page.media_player.setSource(QUrl.fromLocalFile(file_name))
            self.page.media_player.play()
            self.page._update_ui_state(True)

class PlayPauseManager(BaseButtonManager):
    def init_button(self):
        self.button = self.ui.findChild(QPushButton, "pushButton_22")
        if not self.button:
            raise ValueError("播放/暂停按钮未找到")
        return self.button
    
    def connect_signals(self):
        self.button.clicked.connect(self._toggle_playback)
    
    def _toggle_playback(self):
        current_state = self.page.media_player.playbackState()
        
        if current_state == QMediaPlayer.PlayingState:
            self.page.media_player.pause()
        else:
            self.page.media_player.play()
        
class ImageImportManager(BaseButtonManager):
    def init_button(self):
        self.button = self.ui.findChild(QPushButton, "pushButton_25")  # 假设按钮名称
        if not self.button:
            raise ValueError("图片导入按钮未找到")
        return self.button
    
    def connect_signals(self):
        self.button.clicked.connect(self._handle_import)
    
    def _handle_import(self):
        """处理图片导入"""
        file_name, _ = QFileDialog.getOpenFileName(
            None,
            "选择图片文件",
            "",
            "图片文件 (*.png *.jpg *.jpeg *.bmp);;所有文件 (*)"
        )
        
        if file_name:
            try:
                self.page._clear_media_components()  # 先清理原有内容
                self._display_image(file_name)
                self.page._update_ui_state(False, is_image=True)
            except Exception as e:
                print(f"图片加载失败: {str(e)}")

    def _display_image(self, file_path):
        """在widget_13显示图片"""
        container = self.page.ui.findChild(QWidget, "widget_13")
        if not container:
            raise ValueError("图片容器widget_13未找到")
        
        # 清理容器原有内容
        if container.layout():
            QWidget().setLayout(container.layout())  # 移除原有布局
        container.setLayout(QVBoxLayout())
        
        # 创建图片标签
        label = QLabel(container)
        pixmap = QPixmap(file_path)
        
        # 自适应缩放
        scaled_pixmap = pixmap.scaled(
            container.size(), 
            Qt.AspectRatioMode.KeepAspectRatio,
            Qt.TransformationMode.SmoothTransformation
        )
        
        label.setPixmap(scaled_pixmap)
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        container.layout().addWidget(label)

class ClearManager(BaseButtonManager):
    def init_button(self):
        self.button = self.ui.findChild(QPushButton, "pushButton_28")
        if not self.button:
            raise ValueError("清空按钮未找到")
        return self.button
    
    def connect_signals(self):
        self.button.clicked.connect(self._clear_components)
    
    def _clear_components(self):
        """清空视频组件"""
        self.page.media_player.stop()
        self.page.media_player.setSource(QUrl())
        
        # 新增：重置进度条状态
        self.page.horizontalSlider.setRange(0, 0)
        self.page.horizontalSlider.setEnabled(False)  # ✅ 确保清空后不可操作
        
        # 重置时间显示
        self.page.label_current.setText("00:00:00")
        self.page.label_duration.setText("00:00:00")

        container = self.page.ui.findChild(QWidget, "widget_13")
        if container:
            if container.layout():
                while container.layout().count():
                    item = container.layout().takeAt(0)
                    if item.widget():
                        item.widget().deleteLater()

        if self.page.video_widget:
            container = self.page.ui.findChild(QWidget, "widget_13")
            if container and container.layout():
                container.layout().deleteLater()
            self.page.video_widget.deleteLater()
            self.page.video_widget = None
        
        self.page._update_ui_state(False)

class CameraPage:
    def __init__(self, ui_section):
        self.ui = ui_section
        self.media_player = QMediaPlayer()
        self.video_widget = None
        self.video_layout = None
        self.audio_output = QAudioOutput()  
        self.media_player.setAudioOutput(self.audio_output)  

        # 初始化控件管理器
        self._init_managers()
        # 初始化公共组件
        self._init_common_components()
        # 初始化媒体信号连接
        self._init_media_signals()

    def _init_managers(self):
        """初始化所有按钮管理器"""
        self.managers = [
            VideoImportManager(self.ui, self),
            PlayPauseManager(self.ui, self),
            ClearManager(self.ui, self),
            AudioImportManager(self.ui, self),
            ImageImportManager(self.ui, self),
            MuteManager(self.ui, self)
        ]
        
        for manager in self.managers:
            try:
                manager.init_button()
                manager.connect_signals()
            except ValueError as e:
                print(f"按钮初始化错误: {str(e)}")

    def _init_common_components(self):
        """初始化非按钮控件"""
        self.horizontalSlider = self.ui.findChild(QSlider, "horizontalSlider")
        self.comboBox_3 = self.ui.findChild(QComboBox, "comboBox_3")
        
        # 新增: 拖动控制标志位
        self._is_slider_pressed = False 

        # 通过 findChild 获取标签控件
        self.label_current = self.ui.findChild(QLabel, "label_12")  # 当前时间标签
        self.label_duration = self.ui.findChild(QLabel, "label_13")  # 总时长标签
        # 初始化时间显示
        self.label_current.setText("00:00:00")  # 当前时间
        self.label_duration.setText("00:00:00")  # 总时长
        
        # 连接进度条信号（新增三个信号处理）
        self.horizontalSlider.sliderPressed.connect(self._on_slider_pressed)
        self.horizontalSlider.sliderReleased.connect(self._on_slider_released)
        self.horizontalSlider.valueChanged.connect(self._on_slider_moved)

        self._update_ui_state(False)

    def _on_slider_pressed(self):
        """当用户开始拖动时暂停播放"""
        self._is_slider_pressed = True
        if self.media_player.isPlaying():
            self.media_player.pause()

    def _on_slider_released(self):
        """当用户释放滑块时跳转并恢复播放"""
        self._is_slider_pressed = False
        target_pos = self.horizontalSlider.value()
        self.media_player.setPosition(target_pos)
        
        # 恢复原有播放状态（如果之前是播放状态）
        if self.media_player.playbackState() == QMediaPlayer.PausedState:
            self.media_player.play()

    def _on_slider_moved(self, value):
        """实时更新时间显示（不影响播放）"""
        if self._is_slider_pressed:  # 仅在拖动时更新
            self.label_current.setText(self._format_time(value))
    def _init_media_signals(self):
        """连接媒体播放器信号"""
        self.media_player.positionChanged.connect(self._update_slider_position)
        self.media_player.durationChanged.connect(self._update_slider_range)
        self.media_player.playbackStateChanged.connect(self._handle_playback_state)

    def _setup_video_components(self):
        """初始化视频组件"""
        if self.video_widget is None:
            container = self.ui.findChild(QWidget, "widget_13")
            if not container:
                raise ValueError("视频容器 widget_13 未找到")
            
            self.video_layout = QVBoxLayout(container)
            self.video_widget = QVideoWidget()
            self.video_widget.setAttribute(Qt.WA_OpaquePaintEvent)
            self.video_layout.addWidget(self.video_widget)
            self.media_player.setVideoOutput(self.video_widget)
            self.audio_output = QAudioOutput()
            self.media_player.setAudioOutput(self.audio_output)

    def _update_slider_position(self, position):
        """更新进度条位置"""
        self.horizontalSlider.setValue(position)
        # 更新当前播放时间
        current_time = self._format_time(position)
        self.label_current.setText(current_time)  # label_12 显示当前时间

    def _update_slider_range(self, duration):
        """更新进度条范围"""
        self.horizontalSlider.setRange(0, duration)
        self.horizontalSlider.setEnabled(duration > 0)

        # 更新总时长显示
        total_time = self._format_time(duration)
        self.label_duration.setText(total_time)  # label_13 显示总时长

    def _handle_playback_state(self, state):
        """处理播放状态变化"""
        is_playing = state == QMediaPlayer.PlayingState
        
        # 先更新按钮显示状态
        self._update_play_button_state()
        
        # 再更新其他UI状态
        self._update_ui_state(is_playing)

    def _update_play_button_state(self):
        """修复后的按钮状态更新"""
        current_state = self.media_player.playbackState()
        is_playing = current_state == QMediaPlayer.PlayingState
        
        self.managers[1].button.setText("暂停" if is_playing else "播放")
        self.managers[1].button.setIcon(QIcon.fromTheme(
            QIcon.ThemeIcon.MediaPlaybackPause if is_playing 
            else QIcon.ThemeIcon.MediaPlaybackStart
        ))

    def _update_ui_state(self, is_playing, is_image=False):
        """更新UI状态（新增视频存在性判断）"""
        has_media = self.media_player.source().isEmpty() == False or is_image
        
        # 播放/暂停按钮始终可用（当有视频时）
        self.managers[1].button.setEnabled(not is_image and has_media)
        
        # 进度条控制逻辑（有视频即可操作）
        self.horizontalSlider.setEnabled(not is_image and has_media)  # ✅ 修改此处
        
        # 导入按钮在播放时禁用
        self.managers[0].button.setEnabled(not is_playing)

    def on_page_show(self):
        """页面显示时的处理"""
        if self.media_player.isPlaying():
            self.media_player.pause()

    def on_page_leave(self):
        """离开页面时的处理"""
        self.media_player.pause()

    def _format_time(self, milliseconds):
        """将毫秒转换为 时:分:秒 格式"""
        seconds = milliseconds // 1000
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        seconds = seconds % 60
        return f"{hours:02}:{minutes:02}:{seconds:02}"
    
    def _clear_media_components(self):
        """清理所有媒体组件（新增方法）"""
        # 清理视频/音频
        self.media_player.stop()
        self.media_player.setSource(QUrl())
        
        # 清理图片显示
        container = self.ui.findChild(QWidget, "widget_13")
        if container and container.layout():
            # 删除所有子部件
            while container.layout().count():
                item = container.layout().takeAt(0)
                if item.widget():
                    item.widget().deleteLater()
        
        # 清理视频控件
        if self.video_widget:
            self.video_widget.deleteLater()
            self.video_widget = None

class MuteManager(BaseButtonManager):
    def init_button(self):
        self.button = self.ui.findChild(QPushButton, "pushButton_27")
        if not self.button:
            raise ValueError("静音按钮未找到")
        return self.button  

    def connect_signals(self):
        self.button.clicked.connect(self._toggle_mute)
        # 初始化音量图标
        self._updata_mute_icon(self.page.audio_output.isMuted())

    def _toggle_mute(self):
        """切换静音状态"""
        audio_output = self.page.audio_output
        audio_output.setMuted(not audio_output.isMuted())
        self._updata_mute_icon(audio_output.isMuted())

    def _updata_mute_icon(self, is_muted):
        """更新静音图标状态"""
        icon_path = "newProject/icons/mute mode.png" if is_muted else "newProject/icons/outmute.png"
        icon = QIcon(icon_path)
        self.button.setIcon(icon)
        self.button.setIconSize(QSize(30, 30))
        self.button.setToolTip("取消静音"if is_muted else "静音")